import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { Book } from '../services/book-service'
import type { BookSetting } from '../services/setting-service'
import { bookService } from '../services/book-service'

export const useCurrentBookStore = defineStore('currentBook', () => {
  // 状态定义
  const currentBook = ref<Book | null>(null)
  const currentRoute = ref<string>('/book') // 默认打开书籍管理页面
  const lastOpenedBooks = ref<Book[]>([]) // 最近打开的书籍列表
  const settings = ref<BookSetting[]>([]) // 设定列表
  
  // 计算属性
  const hasCurrentBook = computed(() => currentBook.value !== null)
  
  /**
   * 设置当前选中的书籍
   * @param book 书籍对象或null
   */
  function setCurrentBook(book: Book | null) {
    currentBook.value = book
    
    // 保存到本地存储
    if (book && book.id) {
      localStorage.setItem('currentBook', JSON.stringify(book))
      
      // 更新最近打开的书籍列表
      updateLastOpenedBooks(book)
    } else {
      localStorage.removeItem('currentBook')
    }
  }
  
  /**
   * 设置当前路由
   * @param route 路由路径
   */
  function setCurrentRoute(route: string) {
    currentRoute.value = route
    
    // 保存到本地存储
    localStorage.setItem('currentRoute', route)
  }
  
  /**
   * 设置设定列表
   * @param data 设定列表
   */
  function setSettings(data: BookSetting[]) {
    settings.value = data
  }
  
  /**
   * 更新最近打开的书籍列表
   * @param book 书籍对象
   */
  function updateLastOpenedBooks(book: Book) {
    // 从列表中移除已存在的同一本书
    const index = lastOpenedBooks.value.findIndex(b => b.id === book.id)
    if (index !== -1) {
      lastOpenedBooks.value.splice(index, 1)
    }
    
    // 添加到列表开头
    lastOpenedBooks.value.unshift(book)
    
    // 限制列表长度为10
    if (lastOpenedBooks.value.length > 10) {
      lastOpenedBooks.value = lastOpenedBooks.value.slice(0, 10)
    }
    
    // 保存到本地存储
    localStorage.setItem('lastOpenedBooks', JSON.stringify(lastOpenedBooks.value))
  }
  
  /**
   * 从本地存储恢复状态
   * 恢复当前书籍、当前路由和最近打开的书籍列表
   */
  function restoreFromLocalStorage() {
    try {
      // 恢复当前书籍
      const savedBook = localStorage.getItem('currentBook')
      if (savedBook) {
        const parsedBook = JSON.parse(savedBook)
        // 验证书籍对象是否有效，特别是id属性
        if (parsedBook && parsedBook.id) {
          currentBook.value = parsedBook
        } else {
          console.warn('从本地存储恢复的书籍对象无效，缺少id属性')
          // 清除无效的书籍数据
          localStorage.removeItem('currentBook')
        }
      }
      
      // 恢复当前路由
      const savedRoute = localStorage.getItem('currentRoute')
      if (savedRoute) {
        currentRoute.value = savedRoute
      }
      
      // 恢复最近打开的书籍列表
      const savedBooks = localStorage.getItem('lastOpenedBooks')
      if (savedBooks) {
        lastOpenedBooks.value = JSON.parse(savedBooks)
      }
    } catch (error) {
      console.error('从本地存储恢复状态失败:', error)
      // 清除可能损坏的本地存储数据
      localStorage.removeItem('currentBook')
      localStorage.removeItem('currentRoute')
      localStorage.removeItem('lastOpenedBooks')
    }
  }
  
  /**
   * 获取上次打开的书籍
   * @returns 最近打开的书籍对象或null
   */
  function getLastOpenedBook(): Book | null {
    return lastOpenedBooks.value.length > 0 ? lastOpenedBooks.value[0] : null
  }
  
  /**
   * 从后端加载书籍数据
   * @param bookId 书籍ID
   * @returns 加载的书籍对象或null
   */
  async function loadBook(bookId: string) {
    try {
      console.log('开始加载书籍数据，ID:', bookId)
      const response = await bookService.getBookById(parseInt(bookId))
      console.log('书籍数据加载成功:', response.data)
      setCurrentBook(response.data)
      return response.data
    } catch (error) {
      console.error('加载书籍失败:', error)
      return null
    }
  }
  
  /**
   * 清除当前编辑状态
   * 清除当前书籍和路由，并从本地存储中移除
   */
  function clearCurrentState() {
    currentBook.value = null
    currentRoute.value = '/book'
    
    localStorage.removeItem('currentBook')
    localStorage.removeItem('currentRoute')
  }
  
  /**
   * 保存状态到本地存储
   * 保存当前书籍、路由和最近打开的书籍列表
   */
  function saveToLocalStorage() {
    try {
      if (currentBook.value) {
        localStorage.setItem('currentBook', JSON.stringify(currentBook.value))
      }
      localStorage.setItem('currentRoute', currentRoute.value)
      localStorage.setItem('lastOpenedBooks', JSON.stringify(lastOpenedBooks.value))
    } catch (error) {
      console.error('保存状态到本地存储失败:', error)
    }
  }
  
  return {
    // 状态
    currentBook,
    currentRoute,
    lastOpenedBooks,
    settings,
    
    // 计算属性
    hasCurrentBook,
    
    // 方法
    setCurrentBook,
    setCurrentRoute,
    setSettings,
    updateLastOpenedBooks,
    restoreFromLocalStorage,
    getLastOpenedBook,
    loadBook,
    clearCurrentState,
    saveToLocalStorage
  }
})